package cn.wps.solution.demo.controller;

import cn.wps.solution.demo.entity.File;
import cn.wps.solution.demo.entity.FileId;
import cn.wps.solution.demo.repository.FileRepository;
import cn.wps.solution.demo.repository.StorageRepository;
import cn.wps.solution.weboffice.provider.v3.exception.FileNotExist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.Comparator;
import java.util.Optional;

@Controller
@RequestMapping(value = "/console")
public class ConsoleController {
    @Autowired
    private StorageRepository storageRepository;

    @Autowired
    private FileRepository fileRepository;

    @GetMapping(value = "/download/{file_id}/{version}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public @ResponseBody byte[] download(@PathVariable("file_id") String fileId,
                                         @PathVariable("version") int version) {
        return storageRepository.findByFileId(FileId.builder().id(fileId).version(version).build());
    }

    File fetchFile(String fileId) {
        return Optional.ofNullable(fileId)
                .map(fileRepository::findByIdId)
                .map(Collection::stream)
                .flatMap(s -> s.max(Comparator.comparingInt(f -> f.getId().getVersion())))
                .orElseThrow(FileNotExist::new);
    }

    @PutMapping(value = "/upload/{file_id}")
    public @ResponseBody String upload(@PathVariable("file_id") String fileId, @RequestBody byte[] content) {
        // ATTENTION a dirty version is written into storage
        Optional.ofNullable(fileId)
                .map(s -> fetchFile(s))
                .map(f -> f.getId().copyForNewVersion())
                .ifPresentOrElse(fid -> storageRepository.save(fid, content), FileNotExist::new);
        return "ok";
    }
}
